<template>
  <div class="register">
    <nav-bar></nav-bar>
    <el-card>
      <h2 class="title">注册</h2>
      <div class="register_type">
        <div v-for="(item,index) in title"
             :class="{active: index === currentIndex}"
             @click="typeClick(index)">{{item}}
        </div>
      </div>

      <el-form :model="registerForm"
               status-icon
               :rules="rules"
               ref="registerForm"
               label-width="70px"
               class="registerForm">
        <el-form-item label="手机" prop="phone" v-if="!currentIndex">
          <el-input type="phone"
                    placeholder="请输入手机"
                    v-model="registerForm.phone"
                    autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" v-if="currentIndex">
          <el-input type="email"
                    placeholder="请输入邮箱"
                    v-model="registerForm.email"
                    autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="pass">
          <el-input type="password"
                    placeholder="请输入密码"
                    v-model="registerForm.pass"
                    autocomplete="off"
                    show-password></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password"
                    placeholder="请再次输入密码"
                    v-model="registerForm.checkPass"
                    autocomplete="off"
                    show-password></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('registerForm')">注册</el-button>
          <el-button @click="resetForm('registerForm')">重置</el-button>
        </el-form-item>
      </el-form>
      <p>已有账号？<span @click="toLogin">去登录</span></p>
    </el-card>
  </div>
</template>

<script>
  // 公共组件
  import NavBar from "components/content/navBar/NavBar";

  // 类和方法
  import {register} from "network/register";
  import {routerReplaceTimeout, routerReplace} from "common/Utils";

  export default {
    name: "Register",
    components: {
      NavBar
    },
    data() {
      // 正则匹配方法
      let validatePhone = (rule, value, callback) => {
        if (value == "") {
          callback(new Error('账号不能为空'))
        }
        const phoneReg = /^1[3-9][0-9]{9}$/
        if (!phoneReg.test(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      };
      let validateEmail = (rule, value, callback) => {
        if (value == "") {
          callback(new Error('账号不能为空'))
        }
        const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (!emailReg.test(value)) {
          callback(new Error('请输入正确的邮箱'))
        } else {
          callback()
        }
      };
      let validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('密码不能为空'));
        }
        const passReg = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/
        if(!passReg.test(value)) {
          callback(new Error('密码位数为6位以上并且需要包括字母（大小写）、数字、特殊符号'));
        } else {
          if (this.registerForm.checkPass !== '') {
            this.$refs.registerForm.validateField('checkPass');
          }
          callback();
        }
      };
      let validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('确认密码不能为空'));
        } else if (value !== this.registerForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        title: ['手机注册', '邮箱注册'],
        currentIndex: 0,
        registerForm: {
          email: '',
          phone: '',
          pass: '',
          checkPass: '',
        },
        // 匹配规则
        rules: {
          email: [
            {validator: validateEmail, trigger: 'blur'}
          ],
          phone: [
            {validator: validatePhone, trigger: 'blur'}
          ],
          pass: [
            {validator: validatePass, trigger: 'blur'}
          ],
          checkPass: [
            {validator: validatePass2, trigger: 'blur'}
          ],
        }
      };
    },
    methods: {
      /*
      事件监听
       */
      typeClick(index) {
        this.currentIndex = index
        this.resetForm('registerForm')
      },
      /*
      路由跳转
       */
      toLogin() {
        routerReplace(this.$router, '/login')
      },
      /*
      提交、重置表单
       */
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let message = {}
            if(this.registerForm.phone) {
                message = {
                phone: this.registerForm.phone,
                password: this.registerForm.pass
              }
            }else {
                message = {
                email: this.registerForm.email,
                password: this.registerForm.pass
              }
            }
            register(message).then(res => {
              const userInfo = {
                nickname: res.data.data.basicInfo.nickname,
                avatar: res.data.data.basicInfo.avatar,
                phone: res.data.data.basicInfo.phone ? res.data.data.basicInfo.phone : '',
                email: res.data.data.basicInfo.email? res.data.data.basicInfo.email : '',
                id: res.data.data._id,
                isLogin: true
              }

              let timer = setTimeout(() => {
                // 修改Vuex中的状态
                this.$store.commit("setUserInfo", userInfo);//更新userInfo
                clearTimeout(timer)
              }, 1000)

                if(res.data.code) {
                  this.$toast.show('注册成功', 'success', 1000)
                  routerReplaceTimeout(this.$router, '/home', 1000)
                }else {
                  let timer = setTimeout(() => {
                    this.$toast.show('注册失败，该账号已存在', 'failure', 2000)
                    this.resetForm('registerForm')
                    clearTimeout(timer)
                  }, 500)
                }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style scoped>
  .register {
    width: 500px;
    margin: 120px auto 0;
  }

  .title {
    padding-bottom: 25px;
    text-align: center;
    font-size: 24px;
    color: #002766;
  }

  .register_type {
    overflow: hidden;
    margin-bottom: 30px;
  }

  .register_type div {
    float: left;
    width: 50%;
    height: 35px;
    border-bottom: 1px solid #eeeeee;
    line-height: 35px;
    text-align: center;
    color: #8F9395;
    cursor: pointer;
  }

  .register_type div.active {
    color: #002766;
    border-bottom-color: #002766;
  }

  .el-button--primary {
    background-color: #4361a7;
    border-color: #4361a7;
    color: #fff;
  }

  .el-card >>> .el-card__body {
    padding: 30px 40px;
  }

  .el-button--primary:hover {
    background-color: #5177ce;
    border-color: #5177ce;
    color: #fff;
  }

  .el-button--primary {
    margin-right: 10px;
  }

  p {
    margin: -5px 0 0 70px;
    font-size: 12px;
    color: #8F9395;
  }

  p span {
    color: #4361a7;
    cursor: pointer;
  }
</style>
